import React, { useState, useRef, useEffect } from 'react'
import styles from './RotatingAvatar.module.less'

export default function RotatingAvatar({ src, alt = '', className = '' }) {
    const animationFrameRef = useRef(null)
    const rotationRef = useRef(0) // 当前旋转角度
    const imgRef = useRef(null)
    const speedRef = useRef(0) // 当前速度的引用
    const isPressedRef = useRef(false) // 使用 ref 而不是 state 来避免闭包问题

    // 加速和减速的常数
    const ACCELERATION = 0.5 // 加速度
    const DECELERATION = 0.95 // 减速系数
    const MAX_SPEED = 15 // 最大旋转速度
    const MIN_SPEED = 0.1 // 最小速度阈值

    const animate = () => {
        if (isPressedRef.current) {
            // 按住时加速
            speedRef.current = Math.min(speedRef.current + ACCELERATION, MAX_SPEED)
        } else {
            // 松开时减速
            speedRef.current = speedRef.current * DECELERATION
        }

        // 更新旋转角度
        rotationRef.current += speedRef.current

        // 应用旋转
        if (imgRef.current) {
            imgRef.current.style.transform = `rotate(${rotationRef.current}deg)`
        }

        // 如果速度足够大或者还在按住，继续动画
        if (speedRef.current > MIN_SPEED || isPressedRef.current) {
            animationFrameRef.current = requestAnimationFrame(animate)
        } else {
            // 完全停止
            speedRef.current = 0
            animationFrameRef.current = null
        }
    }

    const startRotation = () => {
        isPressedRef.current = true
        if (!animationFrameRef.current) {
            animate()
        }
    }

    const stopRotation = () => {
        isPressedRef.current = false
    }

    // 清理动画帧
    useEffect(() => {
        return () => {
            if (animationFrameRef.current) {
                cancelAnimationFrame(animationFrameRef.current)
            }
        }
    }, [])

    const handleMouseDown = (e) => {
        e.preventDefault()
        startRotation()
    }

    const handleMouseUp = () => {
        stopRotation()
    }

    const handleMouseLeave = () => {
        stopRotation()
    }

    // 处理触摸事件（移动端支持）
    const handleTouchStart = () => {
        startRotation()
    }

    const handleTouchEnd = () => {
        stopRotation()
    }

    const handleTouchCancel = () => {
        stopRotation()
    }

    return (
        <div
            className={`${styles.avatarContainer} ${className}`}
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseLeave}
            onTouchStart={handleTouchStart}
            onTouchEnd={handleTouchEnd}
            onTouchCancel={handleTouchCancel}
        >
            <img
                ref={imgRef}
                src={src}
                alt={alt}
                className={styles.avatarImg}
                draggable={false}
            />
        </div>
    )
}